<template>
  <u-navbar title="数据总览" placeholder @leftClick="back"></u-navbar>
  <view class="approval-statistics" :style="DynamicHeight">

    <view class="approval-statistics-tabs">
      <up-tabs :current="currentTab" :list="tabSlist" @click="tabSclick"></up-tabs>
    </view>

    <view class="approval-statistics-header">
      <view class="header-left" @click="filterClick">
        <view>{{ selectedTime }}</view>
        <up-icon v-if="!filterPopups" name="arrow-down" size="14" color="#000"
          style="margin-left: 2px;font-weight: 700;"></up-icon>
        <up-icon v-else name="arrow-up" size="14" color="#000" style="margin-left: 2px;font-weight: 700;"></up-icon>
      </view>
      <view class="header-divider">|</view>
      <view class="header-date">{{ headerDate }}</view>
    </view>

    <!-- 内容 -->
    <view class="approval-statistics-content" :style="contentDynamicHeight">
      <view class="content-Initiatedbyme">
        <view class="card-header">
          <view class="card-title"> {{ currentTab === 0 ? '我发起的' : '我审批的' }}</view>
        </view>

        <view class="card-body">
          <view class="card-item">
            <view class="value"> {{ currentTab === 0 ? (dataObj?.total || 0) : (dataObj?.total || 0) }}
            </view>
            <view class="label">{{ currentTab === 0 ? '发起单量' : '审批单量' }}</view>
          </view>

          <view class="card-item">
            <view class="value">{{ currentTab === 0 ? (dataObj?.pending || 0) : (dataObj?.pending || 0) }}
            </view>
            <view class="label">待处理</view>
          </view>

          <view class="card-item">
            <view class="value"> {{ currentTab === 0 ? (dataObj.pending || 0) : (dataObj.pending || 0) }}</view>
            <view class="label">已处理</view>
          </view>

          <view class="card-item">
            <view class="value">
              {{ dataObj?.avg_time || 0 }}
              <text style="font-size: 28rpx;">{{ currentTab === 0 ? '小时' : '' }}</text>
            </view>
            <view class="label"> {{ currentTab === 0 ? '流程平均耗时' : '审批节点平均耗时' }}</view>
          </view>
        </view>

        <!-- 折线图 -->
        <view style="width: 100%;;height: 240px;margin-top: 10px;">
          <qiun-data-charts :opts="opts" type="line" :chartData="chartData" :enableScroll="true" :ontouch="true"
            :canvas2d="true" />
        </view>
      </view>


      <view class="content-Mytodolist">
        <view class="card-header">
          <up-tabs :current="currentStatusTab" :list="Mytodolist" @click="switchStatus"></up-tabs>
        </view>
        <view class="card-table-wrapper">
          <scroll-view scroll-x="true" style="width: 100%;">
            <up-table :borderColor="'transparent'" :align="'center'" :padding="'20rpx 0'" :fontSize="'28rpx'">
              <!-- 表头 -->
              <up-tr>
                <up-th>
                  <view class="ellipsis" :style="{ width: '260rpx' }">流程名称</view>
                </up-th>
                <up-th>
                  <view class="ellipsis" :style="{ width: '180rpx' }">状态</view>
                </up-th>
                <up-th>
                  <view class="ellipsis" :style="{ width: '100rpx' }">耗时(h)</view>
                </up-th>
                <up-th>
                  <view class="ellipsis" :style="{ width: '280rpx' }">审批编号</view>
                </up-th>
                <up-th>
                  <view class="ellipsis" :style="{ width: '150rpx' }">提交人</view>
                </up-th>
                <up-th>
                  <view class="ellipsis" :style="{ width: '200rpx' }">创建时间</view>
                </up-th>
                <up-th>
                  <view class="ellipsis" :style="{ width: '200rpx' }">结束时间</view>
                </up-th>
              </up-tr>

              <!-- 数据行纵向滚动 -->
              <scroll-view v-if="filteredTable.length !== 0" scroll-y="true" :style="{ maxHeight: '344rpx' }"
                style="width:1450rpx;">
                <up-tr v-for="item in filteredTable" :key="item.id" style="border-top: 1px solid #efeff1;"
                  @click="vieWdel(item)">
                  <up-td>
                    <view class="ellipsis" :style="{ width: '260rpx' }">{{ item.title }}</view>
                  </up-td>
                  <up-td>
                    <view class="ellipsis" :style="{ width: '180rpx', color: item.statusColor }">
                      {{ item.status_name }}
                    </view>
                  </up-td>
                  <up-td>
                    <view class="ellipsis" :style="{ width: '100rpx' }">{{ item.duration }}</view>
                  </up-td>
                  <up-td>
                    <view class="ellipsis" :style="{ width: '280rpx' }">{{ item.formNo }}</view>
                  </up-td>
                  <up-td>
                    <view class="ellipsis" :style="{ width: '150rpx' }">{{ item.worker_name }}</view>
                  </up-td>
                  <up-td>
                    <view class="ellipsis" :style="{ width: '200rpx' }">{{ item.create_time }}</view>
                  </up-td>
                  <up-td>
                    <view class="ellipsis" :style="{ width: '200rpx' }">{{ item.end_time }}</view>
                  </up-td>
                </up-tr>
              </scroll-view>

              <view v-else style="text-align: center;">
                <view>
                  <image style="width: 135px;height: 135px;" src="@/static/apply/zwsj.png"></image>
                </view>
                <view>暂无数据</view>
              </view>

            </up-table>
          </scroll-view>
        </view>
      </view>
    </view>

    <up-popup :show="filterPopups" @close="filterPopups = false" @open="open">
      <view :style="filterPopupsDynamicHeight" class="member-popup-content">
        <!-- 顶部操作栏 -->
        <view class="popup-header">
          <view class="close-btn" @click="filterPopups = false">

            <up-icon name="close" size="18" color="#26282b"></up-icon>
          </view>
          <view class="title">选择时间</view>
        </view>

        <!-- 内容 -->
        <view class="time-options">
          <view v-for="(item, index) in timeOptions" :key="index"
            :class="['itemView', { 'active': selectedTime === item }]" @click="selectTime(item)">
            {{ item }}
          </view>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script>
import apply from "@/apis/cloud/apply.js";
export default {
  name: 'approvalStatistics',
  data () {
    return {
      height: 0,
      DynamicHeight: {},
      contentDynamicHeight: {},
      filterPopupsDynamicHeight: {},
      filterPopups: false,
      timeOptions: ['本周', '近7天', '上周', '近14天', '本月', '近30天', '上月'],
      selectedTime: '近7天',
      headerDate: '',
      tabSlist: [
        { name: '我发起的', },
        { name: '我审批的', }
      ],
      Mytodolist: [
        { name: "全部", status: 0 },
        { name: "待处理", status: 1 },
        { name: "已处理", status: 2 }
      ],
      currentTab: 0,
      chartData: {},
      //您可以通过修改 config-ucharts.js 文件中下标为 ['line'] 的节点来配置全局默认参数，如都是默认参数，此处可以不传 opts 。实际应用过程中 opts 只需传入与全局默认参数中不一致的【某一个属性】即可实现同类型的图表显示不同的样式，达到页面简洁的需求。
      opts: {
        enableScroll: true,
        color: ["#55bba6", "#3982f5",],
        padding: [0, 15, 0, 0],
        legend: {
          show: true,
          position: 'top',
          color: '#333',
          padding: 13,
        },
        xAxis: {
          disableGrid: true,
          itemCount: 6,
          type: 'grid', // 网格类型
          gridType: 'dash', // 虚线样式
          scrollShow: true, // 显示滚动条
          scrollAlign: 'left', // 滚动条初始位置
          scrollBackgroundColor: '#F7F7FF', // 滚动条背景色
          scrollColor: '#DEE7F7',
        },
        yAxis: {
          gridType: "dash",
          dashLength: 2,
        },
        extra: {
          line: {
            type: "straight",
            width: 2,
            activeType: "hollow"
          }
        }
      },
      startDate: '', // 开始时间
      endDate: '', // 结束时间
      dataObj: {},
      currentStatusTab: 0, // 当前选中的 tab
    }
  },
  onLoad (value) {
    this.currentTab = Number(value.index)
    this.selectedTime = value.selectedTime
    // 默认近7天
    this.updateHeaderDate(this.selectedTime);
  },
  onShow () {
    this.$nextTick(() => {
      if (this.dataObj.line) {
        this.getServerData()
      }
    })
  },
  created () {
    this.height = (uni.getSystemInfoSync().windowHeight || uni.getSystemInfoSync().screenHeight) || 0
    // #ifdef APP-PLUS
    this.DynamicHeight = { height: `${this.height - 75}px`, overflowY: 'hidden' }
    this.contentDynamicHeight = { height: `${this.height - 155}px`, overflowY: 'auto' }
    this.filterPopupsDynamicHeight = { height: `${this.height / 3}px`, overflowY: 'auto' }
    // #endif

    // #ifdef H5
    this.DynamicHeight = { height: `${this.height - 45}px`, overflowY: 'hidden' }
    this.contentDynamicHeight = { height: `${this.height - 125}px`, overflowY: 'auto' }
    this.filterPopupsDynamicHeight = { height: `${this.height / 2.5}px`, overflowY: 'auto' }
    // #endif
  },
  computed: {
    // 根据当前 tab 筛选表格数据
    filteredTable () {
      try {
        if (!this.dataObj.table) {
          uni.hideLoading()
          return []
        }

        const status = this.Mytodolist[this.currentStatusTab].status
        let table = status === 0
          ? this.dataObj.table
          : this.dataObj.table.filter(item => item.status === status)

        // 映射状态文字和颜色
        const statusMap = {
          1: { color: '#3c9cff' },
          2: { color: '#5ac725' },
          3: { color: '#f56c6c' },
          4: { color: '#909399' }
        }

        let data = table.map(item => {
          const info = statusMap[item.status] || { text: '未知', color: '#999' }
          return {
            ...item,
            statusText: info.text,
            statusColor: info.color
          }
        })
        uni.hideLoading()
        return data

      } catch (error) {
        uni.hideLoading()
      } finally {

      }
    },
    apiType () {
      return this.currentTab + 1
    },
  },
  methods: {
    vieWdel (item) {
      uni.navigateTo({
        url: '/pages/apply/oaList/applyOrderDetail?id=' + item.id
      });
    },
    switchStatus (index) {
      this.currentStatusTab = index.index
    },
    async getApplyStatistics () {
      uni.showLoading({
        title: '加载中...'
      });
      try {
        let res = await apply.ApplyStatisticsDetail({
          start: this.startDate,
          end: this.endDate,
          type: this.apiType
        })

        if (res.status == 1) {
          this.dataObj = res.data

        } else {
          uni.showToast({
            title: res.msg || "获取失败",
            icon: 'error'
          })
        }
        this.getServerData();
      } catch (error) {
        uni.showToast({
          title: "获取失败",
          icon: "error",
        });
      } finally {
        // uni.hideLoading()
      }
    },
    async tabSclick (value) {
      this.currentTab = value.index
      await this.getApplyStatistics()
    },
    filterClick () {
      this.filterPopups = true
    },
    // 时间筛选
    selectTime (item) {
      this.selectedTime = item;
      this.updateHeaderDate(item);
      this.filterPopups = false;
    },
    // 更换时间
    async updateHeaderDate (item) {
      const now = new Date();
      let startDate, endDate = now;
      switch (item) {
        case '近7天':
          startDate = new Date(now.getTime() - 6 * 24 * 3600 * 1000);
          break;
        case '本周':
          const day = now.getDay() || 7;
          startDate = new Date(now.getTime() - (day - 1) * 24 * 3600 * 1000);
          break;
        case '上周':
          const d = now.getDay() || 7;
          startDate = new Date(now.getTime() - (d + 6) * 24 * 3600 * 1000);
          endDate = new Date(now.getTime() - d * 24 * 3600 * 1000);
          break;
        case '近14天':
          startDate = new Date(now.getTime() - 13 * 24 * 3600 * 1000);
          break;
        case '本月':
          startDate = new Date(now.getFullYear(), now.getMonth(), 1);
          break;
        case '近30天':
          startDate = new Date(now.getTime() - 29 * 24 * 3600 * 1000);
          break;
        case '上月':
          const firstDayLastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
          const lastDayLastMonth = new Date(now.getFullYear(), now.getMonth(), 0);
          startDate = firstDayLastMonth;
          endDate = lastDayLastMonth;
          break;
      }

      const format = (date, value) => {
        return `${date.getFullYear()}${value ? '-' : '.'}${(date.getMonth() + 1).toString().padStart(2, '0')}${value ? '-' : '.'}${date.getDate().toString().padStart(2, '0')}`;
      }

      this.headerDate = `${format(startDate, false)}-${format(endDate, false)}`;
      this.startDate = format(startDate, true)
      this.endDate = format(endDate, true)
      await this.getApplyStatistics()
    },
    getServerData () {
      let filtered = this.dataObj.line.date.map((d, i) => ({
        date: d.slice(5),
        now: this.dataObj.line.now[i],
        prev: this.dataObj.line.prev[i]
      })).filter(item => !(item.now === 0 && item.prev === 0))

      let res = {
        categories: filtered.map(d => d.date),
        series: [
          { name: this.selectedTime, data: filtered.map(d => d.now) },
          { name: "上期数据", data: filtered.map(d => d.prev) }
        ]
      }
      this.chartData = JSON.parse(JSON.stringify(res)) // 直接赋值，不用置 null
    },
    back () {
      uni.reLaunch({
        url: "/pages/apply/home/index?index=1"
      })
    },
  }
}

</script>

<style lang="scss" scoped>
.approval-statistics {
  overflow-x: hidden;
  color: #19232f;
  width: 100%;
  background-color: #f2f4f8;
  margin: 0;

  // 搜索tabs
  .approval-statistics-tabs {
    width: 100%;
    padding: 0 10px;
    height: 40px;
    background-color: #ffffff;
  }

  // 搜索
  .approval-statistics-header {
    font-size: 30rpx;
    width: 100%;
    padding: 0 10px;
    height: 40px;
    background-color: #ffffff;
    display: flex;
    align-items: center; // 垂直居中
    justify-content: flex-start;

    .header-left {
      margin-top: 2rpx;
      display: flex;
      align-items: center;
    }

    .header-divider {
      padding: 0 10rpx;
      color: #7b7c7e;
    }

    .header-date {
      margin-top: 2rpx;
      color: #7b7c7e;
    }
  }

  // 内容
  .approval-statistics-content {
    overflow: hidden;

    // 我发起的
    .content-Initiatedbyme {
      // #ifdef APP-PLUS
      height: 830rpx;
      // #endif

      // #ifdef H5
      height: 850rpx;
      // #endif
      background-color: #fff;
      margin-top: 10px;
      position: relative;
      padding: 10px 10px 0 10px;

      .card-header {
        display: flex;
        height: 50rpx;

        .card-title {
          font-size: 30rpx;
          color: #19232f;
        }
      }

      .card-body {
        display: flex;
        flex-wrap: wrap;
        /* 自动换行 */
        margin-top: 10rpx;

        .card-item {
          width: 50%;
          text-align: left;
          padding: 10rpx 0;

          .value {
            font-size: 40rpx;
            font-weight: bold;
            color: #19232f;
          }

          .label {
            margin-top: 8rpx;
            font-size: 26rpx;
            color: #7b7c7e;
          }
        }
      }

      .content-title {
        border-radius: 15rpx;
        padding-left: 10px;
        line-height: 60rpx;
        height: 60rpx;
        background-color: #f6f6f6;
        color: #484a4c;
        font-size: 28rpx;
        margin-top: 6px;

        .compare-value {
          color: #6ca1f6;
          margin: 0 5px;
        }
      }
    }


    // 表格
    .content-Mytodolist {
      margin-bottom: 10px;
      // #ifdef APP-PLUS
      height: 520rpx;
      // #endif

      // #ifdef H5
      height: 520rpx;
      // #endif
      background-color: #fff;
      margin-top: 10px;
      position: relative;
      padding: 10px 10px 0 10px;
      overflow: hidden;

      .card-header {
        display: flex;
        height: 50rpx;

        .card-title {
          font-size: 30rpx;
          color: #19232f;
        }

        .card-icon {
          margin-top: 5px;
          position: absolute;
          right: 10rpx;
          top: 14rpx;
        }
      }

      .card-table-wrapper {
        margin-top: 20px;
        position: relative;
      }


      .content-title {
        border-radius: 5px;
        padding: 5px;
        background-color: #f6f6f6;
        display: flex;
        color: #484a4c;
        font-size: 28rpx;
        margin-top: 6px;

        .compare-value {
          color: #f2a64f;
          margin: 0 5px;
        }
      }
    }



  }

  // 弹窗
  .member-popup-content {
    background-color: #fff;
    padding: 0 30rpx;
    box-sizing: border-box;

    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx 0;
      border-bottom: 1rpx solid #f5f5f5;
      position: relative;

      .title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        width: 200rpx;
        text-align: center;
      }

    }



    .time-options {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      padding: 15px;
      justify-content: space-between;

      .itemView {
        width: calc(50% - 5px);
        text-align: center;
        padding: 7px 0;
        border: 1px solid #e0e0e0;
        border-radius: 8px;
        background-color: #fff;
        box-sizing: border-box;
      }

      .itemView.active,
      .header-left .active {
        background-color: #5693f6;
        color: #fff;
      }
    }

  }
}

.ellipsis {
  padding-left: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>